package com.ukao.cashregister.ui.sendFactory;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.mcxtzhang.commonadapter.rv.OnItemClickListener;
import com.ukao.cashregister.R;
import com.ukao.cashregister.adapter.BatchDetailsAdapter;
import com.ukao.cashregister.base.IAdapter;
import com.ukao.cashregister.base.IPage;
import com.ukao.cashregister.base.MvpFragment;
import com.ukao.cashregister.base.PageWrapper;
import com.ukao.cashregister.bean.BatchlistBean;
import com.ukao.cashregister.bean.FactoryBatchBean;
import com.ukao.cashregister.dialog.AllSelectDialogFragment;
import com.ukao.cashregister.dialog.BatchDialogFragment;
import com.ukao.cashregister.dialog.PrintHideDialogFragment;
import com.ukao.cashregister.eventbus.AppEvent;
import com.ukao.cashregister.listener.MyOnItemClickListener;
import com.ukao.cashregister.pesenter.SendFactoryPesenter;
import com.ukao.cashregister.utils.CheckUtils;
import com.ukao.cashregister.utils.ImageUtils;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.view.SendFactoryView;
import com.ukao.cashregister.widget.DividerDecoration;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.ukao.cashregister.R.id.total_count;
import static com.ukao.cashregister.consts.GlobalConsts.SEND_FACTORY_PAGE_SIZE;


public class sendFactoryFragment extends MvpFragment<SendFactoryPesenter> implements SendFactoryView {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    Unbinder unbinder;
    @BindView(R.id.look_factory)
    Button lookFactory;
    @BindView(R.id.clothing_layout)
    TextView clothingLayout;
    @BindView(R.id.order_number)
    TextView orderNumber;
    @BindView(R.id.clothing_barcode)
    TextView clothingBarcode;
    @BindView(R.id.enter_time)
    TextView enterTime;
    @BindView(R.id.serve)
    TextView serve;
    @BindView(R.id.color)
    TextView color;
    @BindView(R.id.state)
    TextView state;
    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(total_count)
    TextView totalCount;
    @BindView(R.id.select_count)
    TextView selectCount;
    @BindView(R.id.all_select)
    Button allSelect;
    @BindView(R.id.batch_entry)
    Button batchEntry;
    @BindView(R.id.twinkling_layout)
    TwinklingRefreshLayout twinklingLayout;
    @BindView(R.id.sortingText)
    TextView sortingText;

    private String mParam1;
    private String mParam2;
    private List<BatchlistBean.ListBean> productData = new ArrayList<>();
    private BatchDetailsAdapter matchDetailsAdapter;
    private List<BatchlistBean.ListBean> poiIData = new ArrayList<>();
    private PageWrapper<BatchlistBean.ListBean> mPageWrapper;
    private String productIds;
    private String moveproductIds;


    public static sendFactoryFragment newInstance(String param1, String param2) {
        sendFactoryFragment fragment = new sendFactoryFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected SendFactoryPesenter createPresenter() {
        return new SendFactoryPesenter(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View mview = inflater.inflate(R.layout.fragment_send_factory, container, false);
        unbinder = ButterKnife.bind(this, mview);
        initView();
        initListener();
        return mview;
    }


    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        totalCount.setText("0");
        selectCount.setText("0");
        twinklingLayout.startRefresh();
    }

    @Override
    protected void initView() {

        sortingText.setVisibility(View.GONE);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(activity));
        matchDetailsAdapter = new BatchDetailsAdapter(activity, poiIData);
        mRecyclerView.addItemDecoration(new DividerDecoration(getActivity(), DividerDecoration.VERTICAL_LIST));
        mRecyclerView.setAdapter(matchDetailsAdapter);

        ImageUtils.setViewWith(_mActivity,clothingLayout,160,0.12f);
        ImageUtils.setViewWith(_mActivity,orderNumber,160,0.15f);
        ImageUtils.setViewWith(_mActivity,clothingBarcode,160,0.17f);
        ImageUtils.setViewWith(_mActivity,enterTime,160,0.22f);
        ImageUtils.setViewWith(_mActivity,serve,160,0.11f);
        //  ImageUtils.setViewWith(activity,color,160,0.1f);
        ImageUtils.setViewWith(_mActivity,state,160,0.11f);
        ImageUtils.setViewWith(_mActivity,money,160,0.11f);
        IPage page = new IPage() {

            @Override
            public void load(int geIndex, int pageSize) {

                mvpPresenter.batchInList(_mActivity, geIndex, pageSize);

            }
        };
        mPageWrapper = new PageWrapper<>(mIAdapter, page);
        page.setPageSize(SEND_FACTORY_PAGE_SIZE);
    }


    IAdapter mIAdapter = new IAdapter() {
        @Override
        public void setDataSource(List data, boolean isNextLoad) {

            matchDetailsAdapter.setDatas(data);

            twinklingLayout.setEnableLoadmore(isNextLoad);


        }

        @Override
        public void loadMoreFinish(List data, boolean isNextLoad) {
            matchDetailsAdapter.addDatas(data);
            twinklingLayout.setEnableLoadmore(isNextLoad);

        }
    };

    @Override
    protected void initListener() {
        super.initListener();
        matchDetailsAdapter.setOnItemClickListener(mOnItemClickListener);
        twinklingLayout.setOnRefreshListener(mRefreshListenerAdapter);

    }


    private RefreshListenerAdapter mRefreshListenerAdapter = new RefreshListenerAdapter() {
        @Override
        public void onRefresh(TwinklingRefreshLayout refreshLayout) {
            super.onRefresh(refreshLayout);

            mPageWrapper.loadPage(true);
        }

        @Override
        public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
            super.onLoadMore(refreshLayout);

            mPageWrapper.loadPage(false);

        }
    };

    private OnItemClickListener mOnItemClickListener = new MyOnItemClickListener()

    {
        @Override
        public void onItemClick(ViewGroup viewGroup, View view, Object o, int i) {
            super.onItemClick(viewGroup, view, o, i);
            BatchlistBean.ListBean item = (BatchlistBean.ListBean) o;
            item.setCheck(!item.isCheck());
            int count = setSelectCount();
            selectCount.setText(count + "");
            matchDetailsAdapter.notifyDataSetChanged();
        }
    };

    public int setSelectCount() {
        int count = 0;
        for (BatchlistBean.ListBean mDataBean : poiIData) {
            if (mDataBean.isCheck()) {
                count = count + 1;
            }

        }
        return count;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.look_factory, R.id.all_select, R.id.batch_entry,R.id.move_batch})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.move_batch:

                StringBuffer mStringBuffer1 = new StringBuffer();
                productData.clear();
                for (BatchlistBean.ListBean item : poiIData) {
                    if (item.isCheck()) {
                        productData.add(item);
                        mStringBuffer1.append(item.getId()).append(",");

                    }

                }
                if (mStringBuffer1.length() == 0) return;
                moveproductIds= mStringBuffer1.deleteCharAt(mStringBuffer1.length() - 1).toString();
                showMoveBatchDialog(false);
                break;
            case R.id.look_factory:

                start(FactoryTabFragment.newInstance("", ""));

                break;
            case R.id.all_select:  /*全选*/

                AllSelectDialogFragment mAllSelectDialog= AllSelectDialogFragment.newInstance("","");
                mAllSelectDialog.show(getChildFragmentManager(),PrintHideDialogFragment.class.getName());

//                int count = 0;
//                int checkCount = 0;
//                for (BatchlistBean.ListBean mDataBean : poiIData) {
//                    if (mDataBean.isCheck()) {
//                        checkCount = checkCount + 1;
//                    }
//
//                }
//                for (BatchlistBean.ListBean mDataBean : poiIData) {
//                    if (checkCount == poiIData.size()) {/*都勾选了*/
//                        count = 0;
//                        mDataBean.setCheck(false);
//                    } else {
//                        count = poiIData.size();
//                        mDataBean.setCheck(true);
//                    }
//                }
//                selectCount.setText(count + "");
//                matchDetailsAdapter.notifyDataSetChanged();
                break;
            case R.id.batch_entry:/*新建*/

                StringBuffer mStringBuffer = new StringBuffer();
                for (BatchlistBean.ListBean mDataBean : poiIData) {
                    if (mDataBean.isCheck()) {
                        mStringBuffer.append(mDataBean.getId()).append(",");
                    }

                }
                if (mStringBuffer.length() != 0) {
                    productIds = mStringBuffer.deleteCharAt(mStringBuffer.length() - 1).toString();
                    mvpPresenter.batchInadd(_mActivity, productIds);
                } else {
                    mvpPresenter.batchInadd(_mActivity, "");
                }

                break;

        }
    }

    private void showMoveBatchDialog(boolean  isMoveALL) {
        BatchDialogFragment mMoveBatchDialog = new BatchDialogFragment();
        Bundle mBundle = new Bundle();
        mBundle.putString(ARG_PARAM1, resources.getString(R.string.move_batch));
        mBundle.putString(ARG_PARAM2, "");
        mBundle.putBoolean(ARG_PARAM3,isMoveALL);
        mMoveBatchDialog.setArguments(mBundle);
        mMoveBatchDialog.show(getChildFragmentManager(), BatchDialogFragment.class.getName());
    }


    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Subscribe
    public void onEvent(AppEvent event) {
        switch (event.getMessage()) {
            case movebatch:
                if (!isVisible)return;
                String moveId = (String) event.getData();
                if (!CheckUtils.isEmpty(moveId) && !CheckUtils.isEmpty(moveproductIds))
                    mvpPresenter.BatchInReladd(_mActivity, moveId, moveproductIds);

                break;
            case allSelect:  /*全选*/
                int     type=(int)event.getData();
                switch (type){
                    case 1:
                       mvpPresenter.buildBatchInReladd();
                        break;
                    case 2:
                        showMoveBatchDialog(true);

                        break;
                }

                break;

            case  allMovebatch:
                String moveIdAll = (String) event.getData();
                if (!CheckUtils.isEmpty(moveIdAll))
                    mvpPresenter.addAllProductBatch(moveIdAll);
                break;


        }

    }

    /**
     * 批次列表
     *
     * @param mDataBean
     */
    @Override
    public void loadSuccess(BatchlistBean mDataBean) {

        mPageWrapper.addDataSource(mDataBean.getList(), mDataBean.getPages());
        totalCount.setText(mDataBean.getTotal() + "");
    }

    @Override
    public void batchEntrySuccess(FactoryBatchBean mDataBean) {

        start(BatchDetailsFragment.newInstance(mDataBean.getId(), mDataBean.getIsFinish(),mDataBean.getProductCnt()));
    }

    @Override
    public void finishLoad() {
        twinklingLayout.finishRefreshing();
          twinklingLayout.finishLoadmore();
    }

    @Override
    public void moveSuccess() {
        twinklingLayout.startRefresh();
    }

    @Override
    public void loadFail(String message) {
        T.show(message);
    }


}
